<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片 -->
    <el-card>
      <!--警告区域-->
      <el-alert title="注意：只允许为第三级分类设置相关参数！"
                type="warning"
                :closable="false"
                show-icon />
      <!--选择商品分类-->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!--选择商品分类的级联选择框-->
          <el-cascader v-model="selectedCateKeys"
                       :options="cateList"
                       :props="cateProps"
                       @change="handleChange"
                       clearable></el-cascader>
        </el-col>
      </el-row>
      <!-- tab页签 -->
      <el-tabs v-model="activeName"
               @tab-click="handleTabClick">
        <el-tab-pane name='many'
                     label="动态参数">
          <!-- 添加动态参数 -->
          <el-button type="primary"
                     :disabled="isBtnDisabled"
                     size="mini"
                     @click="addDialogVisible=true">添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData"
                    border
                    stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item,i) in scope.row.attrVals"
                        :key="i"
                        closable
                        @close='handleClose(i,scope.row)'>{{item}}</el-tag>
                <!-- 输入框 -->
                <el-input class="input-new-tag"
                          v-if="scope.row.inputVisible"
                          v-model="scope.row.inputValue"
                          ref="saveTagInput"
                          size="small"
                          @keyup.enter.native="handleInputConfirm(scope.row)"
                          @blur="handleInputConfirm(scope.row)">
                </el-input>
                <!--添加按钮 -->
                <el-button v-else
                           class="button-new-tag"
                           size="small"
                           @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称"
                             prop="attrName"></el-table-column>
            <el-table-column type="操作">
              <template slot-scope="scope">
                <el-button type="primary"
                           icon="el-icon-edit"
                           size="mini"
                           @click="showEditDialog(scope.row.attrId)">编辑</el-button>
                <el-button type="danger"
                           icon="el-icon-delete"
                           size="mini"
                           @click="delPamas(scope.row.attrId)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane name='only'
                     label="静态属性">
          <!-- 添加静态属性 -->
          <el-button type="primary"
                     :disabled="isBtnDisabled"
                     size="mini"
                     @click="addDialogVisible=true">添加属性</el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData"
                    border
                    stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item,i) in scope.row.attrVals"
                        :key="i"
                        closable
                        @close='handleClose(i,scope.row)'>{{item}}</el-tag>
                <!-- 输入框 -->
                <el-input class="input-new-tag"
                          v-if="scope.row.inputVisible"
                          v-model="scope.row.inputValue"
                          ref="saveTagInput"
                          size="small"
                          @keyup.enter.native="handleInputConfirm(scope.row)"
                          @blur="handleInputConfirm(scope.row)">
                </el-input>
                <!--添加按钮 -->
                <el-button v-else
                           class="button-new-tag"
                           size="small"
                           @click="showInput(scope.row)">+ New Tag</el-button>
              </template></el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称"
                             prop="attrName"></el-table-column>
            <el-table-column type="操作">
              <template slot-scope="scope">
                <el-button type="primary"
                           icon="el-icon-edit"
                           size="mini"
                           @click="showEditDialog(scope.row.attrId)">编辑</el-button>
                <el-button type="danger"
                           icon="el-icon-delete"
                           size="mini"
                           @click="delPamas(scope.row.attrId)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog :title="`添加`+titleText"
               :visible.sync="addDialogVisible"
               width="40%"
               @click="addDialogClosed">
      <!-- 添加参数的对话框 -->
      <el-form :model="addForm"
               :rules="addFormRules"
               ref="addFormRef"
               label-width="100px">
        <el-form-item :label="titleText"
                      prop="attrName">
          <el-input v-model="addForm.attrName"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数对话框 -->
    <el-dialog :title="`修改`+titleText"
               :visible.sync="editDialogVisible"
               width="40%"
               @click="editDialogClosed">
      <!-- 修改参数对话框 -->
      <el-form :model="editForm"
               :rules="editFormRules"
               ref="editFormRef"
               label-width="100px">
        <el-form-item :label="titleText"
                      prop="attrName">
          <el-input v-model="editForm.attrName"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 商品分类列表
      cateList: [],
      // 级联选择框配置对象
      cateProps: {
        value: 'catId',
        label: 'catName',
        children: 'children',
        expandTrigger: 'hover'
      },
      // 级联选择框双向绑定数据
      selectedCateKeys: [],
      // 默认打开的页签
      activeName: 'many',
      // 动态参数列表
      manyTableData: [],
      // 静态属性列表
      onlyTableData: [],
      // 控制添加对话框的显示与隐藏
      addDialogVisible: false,
      // 控制修改对话框的显示与隐藏
      editDialogVisible: false,
      // 添加参数的数据对象
      addForm: {
        attrName: ''
      },
      // 修改的表单对象
      editForm: {},
      // 验证规则
      addFormRules: {
        attrName: [{ required: true, message: '请输入参数名称', trigger: 'blur' }]
      },
      editFormRules: {
        attrName: [{ required: true, message: '请输入参数名称', trigger: 'blur' }]
      }
    }
  },
  created () {
    // 获取所有的商品分类列表
    this.getCateList()
  },
  methods: {
    async getCateList () {
      const { data: res } = await this.$http.post('/api/cate/getByParam', { catLevel: 2 })
      if (res.meta.status !== 207) {
        return this.$message.error('获取商品分类列表失败！')
      } else {
        this.cateList = res.data.list
      }
    },
    // 级联选择框改变时触发
    handleChange () {
      this.getParamsData()
    },
    // tab页签点击事件
    handleTabClick () {
      this.getParamsData()
    },
    async getParamsData () {
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = []
        this.manyTableData = []
        this.onlyTableData = []
      } else {
        const { data: res } = await this.$http.post('/api/attr/getAttrList', { catId: this.cateId, attrSel: this.activeName })
        if (res.meta.status !== 207) {
          return this.$message.error('获取参数列表失败！')
        } else {
          res.data.list.forEach(item => {
            item.attrVals = item.attrVals ? item.attrVals.split(' ') : []
            // 控制文本框的显示与隐藏
            item.inputVisible = false
            // 文本框输入的内容
            item.inputValue = ''
          })
          if (this.activeName === 'many') {
            this.manyTableData = res.data.list
          } else {
            this.onlyTableData = res.data.list
          }
        }
      }
    },
    // 监听添加对话框的关闭事件
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 监听修改对话框的关闭事件
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 点击按钮添加参数
    addParams () {
      this.$refs.addFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.post('/api/attr/addAttr', { catId: this.cateId, attrName: this.addForm.attrName, attrSel: this.activeName })
          if (res.meta.status !== 201) {
            return this.$message.error('添加' + this.titleText + '失败!')
          } else {
            this.$message.success('添加' + this.titleText + '成功!')
            this.addDialogVisible = false
            this.getParamsData()
          }
        }
      })
    },
    // 点击按钮展示修改对话框
    async showEditDialog (attrId) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.post('/api/attr/findById', { attrId: attrId, catId: this.cateId, attrSel: this.activeName })
      if (res.meta.status !== 207) {
        return this.$$message.error('获取' + this.titleText + '失败!')
      } else {
        this.editForm = res.data
      }
    },
    // 点击按钮修改属性
    editParams () {
      this.$refs.editFormRef.validate(async valid => {
        const { data: res } = await this.$http.post('/api/attr/updAttr', { catId: this.cateId, attrId: this.editForm.attrId, attrName: this.editForm.attrName, attrSel: this.activeName })
        if (res.meta.status !== 203) {
          return this.$message.error('修改' + this.titleText + '失败!')
        } else {
          this.getParamsData()
          this.editDialogVisible = false
          return this.$message.success('修改' + this.titleText + '成功!')
        }
      })
    },
    // 删除属性
    async delPamas (attrId) {
      const confirmResult = await this.$confirm('此操作将永久删除该属性, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除操作！')
      } else {
        const { data: res } = await this.$http.get('/api/attr/delAttr?catId=' + this.cateId + '&attrId=' + attrId)
        if (res.meta.status !== 205) {
          return this.$message.error('删除' + this.titleText + '失败!')
        } else {
          this.getParamsData()
          return this.$message.success('删除' + this.titleText + '成功!')
        }
      }
    },
    // 文本框失去焦点或按下Enter键时触发
    async handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attrVals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      // 发起请求保存此次操作
      this.saveAttrVals(row)
    },
    // 按钮切换为输入框
    showInput (row) {
      row.inputVisible = true
      // 获取焦点
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 保存参数项
    async saveAttrVals (row) {
      const { data: res } = await this.$http.post('/api/attr/updAttr', { catId: this.cateId, attrName: row.attrName, attrId: row.attrId, attrVals: row.attrVals.join(' '), attrSel: this.activeName })
      if (res.meta.status !== 203) {
        return this.$message.error('修改参数项失败!')
      } else {
        return this.$message.success('修改参数项成功!')
      }
    },
    // 监听tag标签的关闭
    handleClose (i, row) {
      row.attrVals.splice(i, 1)
      this.saveAttrVals(row)
    }
  },
  computed: {
    isBtnDisabled () {
      if (this.selectedCateKeys.length !== 3) {
        return true
      } else {
        return false
      }
    },
    cateId () {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2]
      } else {
        return null
      }
    },
    titleText () {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}

</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0px;
}
.el-tag {
  margin: 0px 10px;
}
.input-new-tag {
  width: 120px;
}
</style>
